<!-- @Author: NWJ
        Version: 1.0 -->

<template>
  <div class="main-content">
    <div class="message-container" style="user-select: none; padding: 20px;">
      <!-- 站内信列表 -->
      <div class="message-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="未读消息" name="unread">
            <div v-if="unreadMessages.length > 0" class="message-list">
              <el-card v-for="message in unreadMessages" :key="message.id" shadow="hover" @click="markMessageAsRead(message.id)">
                <div class="message-item">
                  <h3 class="message-title">{{ message.title }}</h3>
                  <p class="message-content">{{ message.content }}</p>
                  <div class="message-meta">
                    <span>发送人 ID: {{ message.sendId }}</span>
                    <span class="message-time">{{ formatDate(message.createdAt) }}</span>
                  </div>
                </div>
              </el-card>
            </div>
            <div v-else class="no-messages">暂无未读消息</div>
          </el-tab-pane>
          <el-tab-pane label="已读消息" name="read">
            <div v-if="readMessages.length > 0" class="message-list">
              <el-card v-for="message in readMessages" :key="message.id" shadow="hover">
                <div class="message-item">
                  <h3 class="message-title">{{ message.title }}</h3>
                  <p class="message-content">{{ message.content }}</p>
                  <div class="message-meta">
                    <span>发送人 ID: {{ message.sendId }}</span>
                    <span class="message-time">{{ formatDate(message.createdAt) }}</span>
                  </div>
                </div>
              </el-card>
            </div>
            <div v-else class="no-messages">暂无已读消息</div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 发送站内信表单 -->
      <div class="send-message">
        <h2>发送站内信</h2>
        <el-form :model="messageForm" :rules="rules" ref="messageForm" label-width="80px" class="send-form">
          <el-form-item  prop="acceptId">
            <el-input v-model.number="messageForm.acceptId" placeholder="请输入接收人 ID"></el-input>
          </el-form-item>
          <el-form-item  prop="title">
            <el-input v-model="messageForm.title" placeholder="请输入站内信标题"></el-input>
          </el-form-item>
          <el-form-item  prop="content">
            <el-input v-model="messageForm.content" type="textarea" :rows="4" placeholder="请输入站内信内容"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { showMsg } from '@/utils/showMsg'
import { layout } from '@/utils/layout'

export default {
  components: {
    // 移除 commonGlassCard 依赖
  },
  data()
  {
    return {
      activeTab: 'unread', // 默认显示未读消息
      unreadMessages: [], // 未读消息列表
      readMessages: [], // 已读消息列表
      messageForm: {
        acceptId: null, // 接收人 ID
        title: '', // 标题
        content: '' // 内容
      },
      rules: {
        acceptId: [
          { required: true, message: '请输入接收人 ID', trigger: 'blur' },
          { type: 'number', message: '接收人 ID 必须是数字', trigger: 'blur' }
        ],
        title: [{ required: true, message: '请输入站内信标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入站内信内容', trigger: 'blur' }]
      }
    }
  },
  created()
  {
    this.fetchMessages()
  },
  methods: {
    // 获取已读和未读消息
    async fetchMessages()
    {
      if (!this.$store.getters.isLoggedIn)
      {
        showMsg('登录状态失效', '请重新登录', 'warning')
        this.$router.push('/login')
        return
      }

      try
      {
        const [unreadRes, readRes] = await Promise.all([
          axios.get(`/node/msgs/acter/${this.$store.getters.getUser.id}?isRead=no`),
          axios.get(`/node/msgs/acter/${this.$store.getters.getUser.id}?isRead=yes`)
        ])
        this.unreadMessages = unreadRes.data.data || []
        this.readMessages = readRes.data.data || []
      }
      catch (error)
      {
        layout(this, true, '登录态失效')
      }
    },

    // 标记消息为已读
    async markMessageAsRead(messageId)
    {
      try
      {
        await axios.patch(`/node/msgs/read/${messageId}`)
        showMsg('消息已读', '已成功标记消息为已读', 'success')
        this.fetchMessages()
      }
      catch (error)
      {
        layout(this, true, '登录态失效')
      }
    },

    // 发送站内信
    async sendMessage()
    {
      this.$refs.messageForm.validate(async(valid) =>
      {
        if (valid)
        {
          if (!this.$store.getters.isLoggedIn)
          {
            showMsg('登录状态失效', '请重新登录', 'warning')
            this.$router.push('/login')
            return
          }
          const payload = {
            sendId: this.$store.getters.getUser.id,
            acceptId: this.messageForm.acceptId,
            title: this.messageForm.title,
            content: this.messageForm.content,
            createdAt: new Date()
          }
          try
          {
            await axios.post('/node/msgs/add', payload)
            showMsg('发送成功', '站内信已成功发送', 'success')
            // 清空表单
            this.messageForm = { acceptId: null, title: '', content: '' }
            this.$refs.messageForm.resetFields()
          }
          catch (error)
          {
            layout(this, true, '发送失败', '站内信发送失败，请重新登录')
          }
        }
      })
    },

    // 切换标签时刷新数据
    handleTabChange()
    {
      this.fetchMessages()
    },

    // 格式化时间
    formatDate(dateString)
    {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
    }
  }
}
</script>

<style scoped>
.main-content {
  height: calc(100vh - 100px);
  overflow: hidden;
  margin-left: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.message-container {
  width: 1000px;
  height: calc(100vh - 160px); /* 调整高度以适配页面布局 */
  background: rgba(255, 255, 255, 0.9); /* 轻微透明背景 */
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow-y: auto; /* 启用纵向滚动 */
  padding: 20px;
  scrollbar-width: thin; /* 细滚动条（Firefox） */
  scrollbar-color: #425aef #f1f1f1; /* 滚动条颜色（Firefox） */
}

/* 自定义滚动条样式（Chrome、Safari） */
.message-container::-webkit-scrollbar {
  width: 8px;
}

.message-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.message-container::-webkit-scrollbar-thumb {
  background: #425aef; /* 滑块颜色 */
  border-radius: 4px;
}

.message-container::-webkit-scrollbar-thumb:hover {
  background: #3548b5; /* 悬停时颜色变深 */
}

.message-tabs {
  margin-bottom: 20px;
}

.message-list {
  max-height: calc(100vh - 340px); /* 确保列表有足够空间，留出发送表单位置 */
  overflow-x: hidden;
}

.message-item {
  cursor: pointer;
  padding: 10px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  text-align: left;
}

.message-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  text-align: left;
  white-space: pre-wrap; /* 保留换行和空格 */
  word-break: break-word; /* 确保长文本换行 */
  margin-bottom: 10px;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.message-time {
  margin-left: 10px;
}

.no-messages {
  text-align: center;
  color: #999;
  padding: 20px;
  font-size: 16px;
}

.send-message {
  margin-top: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.send-message h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 15px;
}

.send-form {
  width: 100%;
}

.el-card {
  margin-bottom: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-card:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-timeline-item__timestamp {
  font-size: 12px;
  color: #999;
}
</style>
